<?php
class PageController extends Controller
{
    protected $page;
    protected $path;
    protected $originPath;
    protected $query;
    protected $host;
    protected $blocks;

    public function PageController($path)
    {
        $this->config = $this->GetConfig();
        $this->host = array_key_exists($this->config->HOST, $this->config->DOMAIN_ALIAS) ? $this->config->DOMAIN_ALIAS[$this->config->HOST] : $this->config->HOST;
        $this->path = $path ? $this->host.FS.$path : $this->host;
        $this->originPath = $this->path = String::RemoveTrailingSlash($this->path);
        $this->LoadPage();
        if ($this->page)
        {
            $this->resourceId = $this->page['resource_id'];
            parent::__construct();
            $this->title = $this->page['title'] ? $this->page['title'] : String::Humanize($this->page['name']);
            $this->metaKeywords = $this->page['meta_keywords'];
            $this->metaDescription = $this->page['meta_description'];
            $this->Redirect();
            $this->Route();
        }
    }

    protected function RegExRoute()
    {
        foreach (AppConfig::GetInstance()->URL_ROUTES as $pattern => $replace)
        {
            $pattern = str_replace('?', '([^/]*)', $pattern);
            $pattern = str_replace('/', '\/', $pattern);
            $url = preg_replace("/$pattern/", $replace, $this->path, -1, $count);
            if ($count > 0)
            {
                $parsed = parse_url($url);
                $this->path = $parsed['path'];
                parse_str(array_get($parsed, 'query'), $this->query);
                $_GET = array_merge($this->query, $_GET);
                $_REQUEST = array_merge($this->query, $_REQUEST);
                break;
            }
        }
    }

    public function Redirect()
    {
        if ($this->page['redirect'])
            RequestHandler::Redirect($this->page['redirect']);
    }

    public function Route()
    {
        if ($this->page['route'])
        {
            $parsed = parse_url($this->page['route']);
            $this->path = String::BeginWith(FS, $parsed['path']) ? $this->host.$parsed['path'] : $parsed['path'];
            parse_str(array_get($parsed, 'query'), $this->query);
            $_GET = array_merge($this->query, $_GET);
            $_REQUEST = array_merge($this->query, $_REQUEST);
            $this->LoadPage();
            $this->title = $this->page['title'] ? $this->page['title'] : $this->title;
            $this->metaKeywords = $this->page['meta_keywords'] ? $this->page['meta_keywords'] : $this->metaKeywords;
            $this->metaDescription = $this->page['meta_description'] ? $this->page['meta_description'] : $this->metaDescription;
        }
    }

    protected function LoadPage()
    {
        $this->RegExRoute();
        $this->page = CmsPageModel::GetEnabledPageByPath($this->path);
    }

    public function RenderPage()
    {
        $this->cache = new CachePage($this->originPath, $this->page);
        return $this->RenderCache();
    }

    public function DoRenderPage()
    {
        $this->config->SetTemplate($this->page['template']);

        if (RequestHandler::GetInstance()->subUrl)
        {
            $out = $this->RenderSubRequest();
        }
        else
        {
            if ($this->page['php_code']) eval($this->page['php_code']);

            $this->LoadLayout();
            if ($this->layout)
            {
                $this->ReplaceLayout('body_id', $this->page['body_id']);
                $this->ReplaceBlocks();
                $out = $this->Render();
            }
            else
            {
                $out = $this->page['content'];
            }
        }
        return $this->Translate($out);
    }

    protected function ReplaceBlocks()
    {
        $this->ReplaceLayout('center', $this->page['content'].'[:center:]');
        $blocks = CmsPageModel::GetInstance()->GetBlocks($this->page['id']);
        foreach ($blocks as $block)
        {
            $this->LoadBlock($block);
        }
        $this->ReplaceLayout($this->blocks);

        $pos = CmsBlockPositionModel::GetInstance()->Find();
        foreach ($pos as $p) $this->ReplaceLayout($p['id'], null);
    }

    protected function LoadBlock($block)
    {
        $content = null;
        $blockName = $block['name'];
        $style = $block['style'];
        $position = $block['position'];
        try
        {
            switch ($block['block_type'])
            {
                case CmsBlockTypeModel::$BLOCKTYPE_CONTROL:
                    using($blockName);
                    $control = new $blockName();
                    $content = $control->Render();
                    break;
                case CmsBlockTypeModel::$BLOCKTYPE_CONTROL:
                    $content = $block['content'];
                    break;
                case CmsBlockTypeModel::$BLOCKTYPE_ELEMENT:
                    $content = CmsPageBlockModel::GetInstance()->GetElementFile($block);
                    break;
            }
        }
        catch (UsingFailedException $ex)
        {
            MessageBase::Exception($ex);
        }
        $content = "<div class='block_$blockName' style='$style'>$content</div>";
        $this->blocks[$position] = isset($this->blocks[$position]) ? $this->blocks[$position].$content : $content;
    }

    protected function LoadLayout()
    {
        $layout = $this->page['layout'];
        $this->layout = $layout ? new $layout() : null;
    }

    public function PageExisted()
    {
        return $this->page;
    }

    protected function GetLayout()
    {}
}
?>